package com.bluemsun.naturallanguageprocessing.service.impl;

import com.bluemsun.naturallanguageprocessing.common.ResponseCode;
import com.bluemsun.naturallanguageprocessing.common.ServerResponse;
import com.bluemsun.naturallanguageprocessing.dao.UserMapper;
import com.bluemsun.naturallanguageprocessing.dao.WeChatUserMapper;
import com.bluemsun.naturallanguageprocessing.entity.User;
import com.bluemsun.naturallanguageprocessing.entity.UserApi;
import com.bluemsun.naturallanguageprocessing.exception.UserNullException;
import com.bluemsun.naturallanguageprocessing.service.IUserService;
import com.bluemsun.naturallanguageprocessing.util.ConductRedisUtil;
import com.bluemsun.naturallanguageprocessing.util.JsonUtil;
import com.bluemsun.naturallanguageprocessing.util.RedisUtil;
import com.bluemsun.naturallanguageprocessing.vo.PageVO;

import com.mysql.cj.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

/**
 * @author ：hj
 * @date ：Created in 2020/11/15 15:04
 * @description：
 * @modified By：
 * @version: $
 */
@Service("userService")
public class UserServiceImpl implements IUserService {

    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;
    @Resource
    private WeChatUserMapper weChatUserMapper;
    @Resource
    private ConductRedisUtil conductRedisUtil;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public ServerResponse<Object> checkUser(User user) {
      if(user.getPassword()!=null&&user.getUsername()!=null){
          //是否有对应的人
          User user1 = userMapper.selectLogin(user.getUsername(),user.getPassword());
          if(user1!= null){
              //将密码设为空，防止泄露密码
              user1.setPassword(null);
              return  ServerResponse.createBySuccess(ResponseCode.SUCCESS.getDesc(),user1);
          }
          return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
      }
      return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
    }

    @Override
    public ServerResponse<Object> registerUser(User user) {
        if(userMapper.checkUsername(user.getUsername())!=0){
            return  ServerResponse.createByErrorMessage("用户名被注册");
        }
        if(userMapper.checkPhone(user.getPhoneNum())!=0){
            return  ServerResponse.createByErrorMessage("电话号码被注册");
        }
        try {
            userMapper.registerUser(user);
            logger.info("test");
        } catch (Exception exception) {
            logger.error("error",exception);

        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ServerResponse<Object> updateUser(UserApi user, HttpServletRequest request) {

            UserApi userApi= conductRedisUtil.getUserFromRedis(request.getHeader("token"));
            if(userApi.getId()==user.getId()) {
                weChatUserMapper.updateById(user);
                UserApi userApi1=weChatUserMapper.selectById(userApi.getId());
                redisUtil.setEx(request.getHeader("token"), JsonUtil.obj2String(userApi1),60*60*24*365);
                return ServerResponse.createBySuccessMessage("更新成功");
            }
            return ServerResponse.createByErrorMessage("越权更改他人");
    }

//    @Override
//    public ServerResponse<Object> selectUser(String username, Integer pageSize, Integer pageNum) {
//        //模糊查询总数
//        int totalRecord= userMapper.countSelectUser(username);
//        //未找到相关用户
//        if(totalRecord==0){
//            return ServerResponse.createByErrorMessage("没有找到相关用户");
//        }
//        PageVO<User> page = new PageVO(pageNum,pageSize,totalRecord);
//        List<User> userList = userMapper.selectUser(username,pageSize,page.getStartIndex());
//        page.setList(userList);
//        return ServerResponse.createBySuccess("成功查询",page);
//    }
//    @Override
//    public ServerResponse<Object> selectAllUser(Integer pageSize, Integer pageNum) {
//        //模糊查询总数
//        int totalRecord= userMapper.countUser();
//        //未找到相关用户
//        if(totalRecord==0){
//            return ServerResponse.createByErrorMessage("没有找到相关用户");
//        }
//        PageVO<User> page = new PageVO(pageNum,pageSize,totalRecord);
//        List<User> userList = userMapper.selectAllUser(pageSize,page.getStartIndex());
//        page.setList(userList);
//        return ServerResponse.createBySuccess("成功查询",page);
//    }
///**
// * @author     ：hj
// * @date       ：Created in 2021/2/7 23:03
// * @description：根据openID查看是否授权
// * @modified By：
// * @version:
// */
    @Override
    public UserApi selectByOpenId(String openId) {
        UserApi userApi = null;
        try {
            userApi=weChatUserMapper.selectByOpenId(openId);
            if(userApi==null)return null;
            userApi.setPassword(null);
            userApi.setOpenId(null);
        } catch (Exception exception) {
            logger.error("UserInfo error",exception);
        }
        return userApi;
    }
/**
 * @author     ：hj
 * @date       ：Created in 2021/2/7 23:04
 * @description：更新
 * @modified By：
 * @version:
 */
    @Override
    public Integer updateById(UserApi userApi) {
        Integer isNull=null;
        try{
            isNull = weChatUserMapper.updateById(userApi);
        }catch(Exception exception){
            logger.error("updateUser error:",exception);
        }
        return isNull;
    }

    @Override
    public Integer insert(UserApi userApi) {
        Integer isSuccess=null;
        try{
            isSuccess = weChatUserMapper.insert(userApi);
        }catch(Exception exception){
            logger.error("insertUser error:",exception);
        }
        return isSuccess;
    }

    @Override
    public UserApi getUserInfo(HttpServletRequest request) {
        UserApi userApi= conductRedisUtil.getUserFromRedis(request.getHeader("token"));
        return userApi;
    }

    @Override
    public ServerResponse isLogin(HttpServletRequest request) {
        //有token值
        String jsonUser = redisUtil.get(request.getHeader("token"));
        if (StringUtils.isNullOrEmpty(jsonUser)){
            return ServerResponse.createByErrorCodeMessage(2,"用户过期");
        }
        else {
            UserApi userApi= conductRedisUtil.getUserFromRedis(request.getHeader("token"));
            if(userApi==null){
                return ServerResponse.createByErrorCodeMessage(1,"用户已过期");
            }
            return ServerResponse.createBySuccess();
        }

    }
}

